﻿using SuperSocket.WebSocket;
using System.Collections.Generic;
using System.Timers;

namespace MyServer.Code
{
    /// <summary>
    /// 消息处理器
    /// </summary>
    public class MessageHandler
    {
        public static MessageHandler Instance { get { return Singleton<MessageHandler>.Instance; } }

        /// <summary>
        /// 计时器
        /// </summary>
        public Timer timer = null;

        /// <summary>
        /// 打开消息处理器
        /// </summary>
        public void Open()
        {
            timer.StartTimer(Broadcast, CommonData.UPDATE_INTERVAL);
        }

        /// <summary>
        /// 关闭消息处理器
        /// </summary>
        public void Close()
        {
            timer.CloseTimer(Broadcast);
        }

        /// <summary>
        /// 广播到客户端
        /// </summary>
        public void Broadcast(object source, ElapsedEventArgs e)
        {
            MySocketManager manager = MySocketManager.Instance;
            if (manager == null || manager.Socket == null)
                return;

            IEnumerable<WebSocketSession> allSession = manager.Socket.GetAllSessions();
            foreach (WebSocketSession session in allSession)
            {
                session.Send(MsgType.同步, new ResultData(false, "同步..."), false);
            }
        }
        
        /// <summary>
        /// 处理协议
        /// </summary>
        /// <param name="type">协议号</param>
        /// <param name="data">协议内容</param>
        public void HandleMessage(WebSocketSession session, MsgType type, byte[] data)
        {
            if (type != MsgType.同步)
            {
                Tool.Log("————————————————————");
                Tool.Log(Common.FormatSocket(false, type, data));
            }
            switch (type)
            {
                case MsgType.回调:
                    {
                        string res = data.DeSerialize<string>();
                        session.Send(type, res.Format());
                    }
                    break;
                case MsgType.连接:
                    {
                        ResultData res = data.DeSerialize<ResultData>();
                        res.info = res.info.Format();
                        session.Send(type, res);
                        break;
                    }
                default:
                    {
                        Tool.Log(type.ToString().Format() + "没有对应处理方法！");
                    }
                    break;
            }
        }
    }
}
